package com.fate.box
import io.flutter.embedding.android.FlutterActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import com.huawei.hms.aaid.HmsInstanceId
import com.huawei.hms.common.ApiException
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    var tag = "MainActivity";
    private val mainHandler = Handler(Looper.getMainLooper())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getToken();
    }
    private fun getToken() {
        // 创建一个新线程
        object : Thread() {
            override fun run() {
                try {
                    // 从agconnect-services.json文件中读取APP_ID
                    val appId = "108914963"
                    // 输入token标识"HCM"
                    val tokenScope = "HCM"
                    val  token = HmsInstanceId.getInstance(this@MainActivity).getToken(appId, tokenScope);
                    Log.i(tag, "MainActivity 获取到华为的token是:$token")
                    // 判断token是否为空
                    if (!TextUtils.isEmpty(token)) {
                        sendRegTokenToServer(token)
                    }
                } catch (e: ApiException) {
                    Log.e(tag, "获取华为token失败, $e")
                }
            }
        }.start()
    }
    private fun sendRegTokenToServer(token: String) {
        Log.i(tag, "sending token to server. token:$token")
        mainHandler.post {
            var engine = FlutterIMApplication.getFlutterEngine()
            val channel = MethodChannel(engine.dartExecutor.binaryMessenger,"com.example.app/get/token")
            channel.invokeMethod("onTokenReceived",token)
        }
    }
}
